package com.ma.controller;

import com.ma.pojo.doubleNode;

/**
 * 双向链表的业务逻辑
 * @param <T>
 */
public class doubleNodeController<T> {

    public doubleNode<T> head;//头
    public doubleNode<T> tail;//尾



    public T peek(){
        if(this.tail==null){
            throw new RuntimeException("栈为空！");
        }
        tail=tail.last;
        return this.tail.next.data;
    }

    /**
     * 反转双向链表
     * @param head
     * @return
     */
    public doubleNode<T> reverse(doubleNode<T> head){

        doubleNode<T> pre=null;

        doubleNode<T> next=null;

        while (head!=null){
            next=head.next;
            head.next=pre;
            head.last=next;
            pre=head;
            head=next;

        }
        return pre;

    }

    /**
     * 从头添加
     * @param value
     */
    public void addFromHead(T value) {
        doubleNode<T> cur = new doubleNode<T>(value);
        if (head == null) {
            head = cur;
            tail = cur;
        } else {
            cur.next = head;
            head.last = cur;
            head = cur;
        }
    }

    /**
     * 从尾添加
     * @param value
     */
    public void addFromTail(T value) {
        doubleNode<T> cur = new doubleNode<T>(value);
        if (head == null) {
            head = cur;
            tail = cur;
        } else {
            cur.last = head;
            tail.next = cur;
            tail = cur;
        }
    }
    /**
     * 从头删除
     */
    public T removeFromHead() {

        if (head == null) {
            return null;
        }
        doubleNode<T> cur=head;
        if(head==tail){
            head=null;
            tail=null;

        } else {
          head=head.next;
          cur.next=null;
          head.last=null;
        }
        return cur.data;

    }
    /**
     * 从尾删除
     */
    public T removeFromTail() {

        if (tail == null) {
            return null;
        }
        doubleNode<T> cur=tail;
        if(head==tail){
            head=null;
            tail=null;

        } else {
            tail=tail.last;
            cur.last=null;
            tail.next=null;
        }
        return cur.data;

    }

}
